// index.js
var util = require('../../utils/util.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    indicatorDots: true,
    autoplay: true,
    interval: 3000,
    duration: 500,
    loadingHidden: false, // loading
    swiperCurrent: 0,
    selectCurrent: 0,
    CurrentPage: 1,
    goodsResult: [],
    classify: [],
    scrollTop: "0",
    loadingMoreHidden: false,
    fromuid: 0,//通过分享带来的分享人ID
    caseArry: [],
    caseArry2: [],
    newslist: [],
    newslist2: [],
    newsone: [],
    newstwo: [],
    categories: [],
    newsArray: [],
    selList: '',//选中的购物车项键列表
    Config: [],
    videoSrc: '',
    supportCompany: "",
    supportPhone: "",
    swiper_h: 1,
    GroupBuyProduct: [],
    DisplayPosition: 0,
    titleImg: "",
    pathGoods: "",
    positionBtnO: {},
    positionBtnTw: {},
    positionBtnTh: {},
    positionBtnF: {},
    contact: false,
    searchbg: "",
    classifyNav: [],
    navDisplayType: 0,
    scrollLeft: 0,
    logo: ""
  },

  /**
   * 首页定制商品展示
   */
  GetGoodsList: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Store/GetWidgetList?storeId=' + app.globalData.storeId + '&code=index_product',
      success: function (res) {
        if (res.data.Code == 0) {
          var Config = res.data.Data.Config
          for (var i = 0; i < Config.length; i++) {
            Config[i].ShowImg = app.globalData.image_logo_banner + Config[i].ShowImg
            Config[i].DisplayProductList = []
            var ProductInfos = Config[i].DisplayProductInfos
            for (var j = 0; j < ProductInfos.length; j++) {
              var h = {}
              h.Pid = ProductInfos[j].Pid
              h.Name = ProductInfos[j].Name
              h.ShowImg = app.globalData.image800_800host + ProductInfos[j].ShowImg
              h.ShopPrice = ProductInfos[j].ShopPrice
              h.SaleCount = ProductInfos[j].SaleCount
              h.MarketPrice = ProductInfos[j].MarketPrice
              h.StoreCid = ProductInfos[j].StoreCid
              h.SKUGid = ProductInfos[j].SKUGid
              h.StockNumber = ProductInfos[j].StockNumber
              if (ProductInfos[j].SKUGid == 0) {
                Config[i].DisplayProductList.push(h)
              }
              else {
                if (!that.checkProduct(Config[i].DisplayProductList, ProductInfos[j].SKUGid)) {
                  Config[i].DisplayProductList.push(h)
                }
              }
            }
          }
          that.setData({
            Config: Config
          })
        }
      }
    })
  },
  //sku产品去重
  checkProduct: function (productList, text) {
    var state = false;  //默认不存在
    if (productList.length > 0 & text != 0) {
      for (var i = 0; i < productList.length; i++) {
        if (text == productList[i].SKUGid) {
          state = true; //已经存在
          break;
        }
      }
    }
    return state;
  },


  /**
 * 获取拼团商品列表
 */
  getGroupBuyProduct: function () {
    var that = this
    wx.request({
      url: app.globalData.host + '/api/Store/GetGroupBuyIndexProduct?storeId=' + app.globalData.storeId,
      success: function (res) {
        if (res.data.Code == 0) {
          var pruduct = []
          var ProductList = res.data.Data.Items
          var rawData = res.data.Data.Page;
          for (var i = 0; i < ProductList.length; i++) {
            if (ProductList[i].Product) {
              var c = {}
              c.Pid = ProductList[i].Product.Pid
              c.Name = ProductList[i].Product.Name
              c.ShowImg = app.globalData.image800_800host + ProductList[i].Product.ShowImg
              c.SaleCount = ProductList[i].Product.SaleCount
              c.ShopPrice = ProductList[i].Product.ShopPrice
              c.StoreCid = ProductList[i].Product.StoreCid
              pruduct.push(c)
            }
          }
          if (res.data.Data.Setting.ShowImg) {
            var titleImg = 'http://static.711688.net.cn/upload/store/' + app.globalData.storeId + '/logo/source/' + res.data.Data.Setting.ShowImg
          } else {
            var titleImg = ""
          }
          that.setData({
            GroupBuyProduct: pruduct,
            DisplayPosition: res.data.Data.Setting.DisplayPosition,
            titleImg: titleImg,
            showIndex: res.data.Data.Setting.ShowIndex
          })
        }
      }
    })
  },
  toGroupbuyTap: function (e) {
    wx.navigateTo({
      url: "/pages/pintuan-details/index?id=" + e.currentTarget.dataset.id
    })
  },


  selectCoupon: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var c = that.data.validCouponList[index];
    wx.setStorageSync(that.data.selList, c);
    wx.navigateBack({
      delta: 1
    })
  },
  /**
   * 领取优惠券
   */
  getCoupon: function (e) {
    var that = this;
    var index = e.currentTarget.dataset.index;
    var couponType = that.data.typeList[index];
    wx.request({
      url: app.globalData.host + '/api/coupon/GetCoupon',
      data: {
        couponTypeId: couponType.CouponTypeId,
        uid: app.globalData.userInfo.Uid
      },
      success: function (res) {
        if (res.data.Code == 0) {
          wx.showModal({
            title: '提示',
            content: '领取成功',
            showCancel: false
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.data.Message,
            showCancel: false
          })
        }
      }
    })
  },


  toDetailsTap: function (e) {
    wx.navigateTo({
      url: "/pages/goods-details/index?id=" + e.currentTarget.dataset.id
    })
  },
  tapBanner: function (e) {
    var id = e.currentTarget.dataset.id
    var name = e.currentTarget.dataset.name
    var linktype = e.currentTarget.dataset.linktype
    var url = e.currentTarget.dataset.url
    var mobile = e.currentTarget.dataset.mobile
    if (id != 0) {
      if (linktype == "product") {//产品详情
        wx.navigateTo({
          url: "/pages/goods-details/index?id=" + id,
        })
      }
      else if (linktype == "store_class") {//产品分类
        wx.navigateTo({
          url: "/pages/classesTwo/index?id=" + id + "&&name=" + name,
        })
      }
      else if (linktype == "news") {//新闻详情
        wx.navigateTo({
          url: '/pages/news-details/index?newsid=' + id,
        })
      }
      else if (linktype == "news_type") {//新闻列表
        wx.navigateTo({
          url: '/pages/news-list/index?newstypeid=' + id,
        })
      }
      else if (linktype == "page" && id == 1) {//优惠劵
        wx.navigateTo({
          url: url
        })
      }
      else if (linktype == "page" && id == 2) {//关于
        wx.setStorageSync("tap", 0);
        wx.reLaunch({
          url: url
        })
      }
      else if (linktype == "page" && id == 3) {//在线客服
        wx.navigateTo({
          url: url
        })
      }
      else if (linktype == "page" && id == 4) {//申请分销
        wx.navigateTo({
          url: url
        })
      }
      else if (linktype == "page" && id == 5) {//预约留言
        wx.navigateTo({
          url: url
        })
      }
      else if (linktype == "page" && id == 6) {//联系方式
        wx.setStorageSync("tap", 1);
        wx.reLaunch({
          url: url
        })
      }
      else if (linktype == "page" && id == 7) {//一键导航
        wx.setStorageSync("tap", 2);
        wx.reLaunch({
          url: url
        })
      }
      else if (linktype == "page" && id == 8) {//拼团
        wx.navigateTo({
          url: url
        })
      }
      else if (linktype == "page" && id == 9) {//限时秒杀
        wx.navigateTo({
          url: url
        })
      }
      else if (linktype == "page" && id == 10) {//留言管理
        wx.navigateTo({
          url: url
        })
      }
      else if (linktype == "page" && id == 11) {//所有商品
        wx.navigateTo({
          url: url
        })
      }
      else if (linktype == "page" && id == 13) {//附近门店
        wx.navigateTo({
          url: url
        })
      }
      else {
        wx.navigateTo({
          url: url
        })
      }
    }
    else if (id == 0 && linktype == "h5page") {//h5网页
      wx.navigateTo({
        url: '/pages/h5page/index?url=' + url,
      })
    }
    else if (id == 0 && linktype == "phonecall") {//一键拨号
      wx.makePhoneCall({
        phoneNumber: mobile
      })

    } else if (id == 0 && linktype == "weappfunc") {//客服会话
      this.setData({
        contact: true
      })
    }
    else {
      wx.navigateTo({
        url: url
      })
    }
  },
  /**
   * 获取店铺信息
   */
  GetVideoInfo: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/Store/GetInfo?id=' + app.globalData.storeId,
      success: function (res) {
        console.log(res)
        if (res.data.Code == 0) {
          that.setData({
            videoSrc: res.data.Data.VideoSrc,
            logo: res.data.Data.Logo,
            supportCompany: res.data.Data.SupportCompany,
            supportPhone: res.data.Data.SupportPhone
          })
        }
      }
    })
  },
  //拨打服务商电话
  callCompany: function () {
    var that = this;
    if (that.data.supportPhone == '') {
      return
    } else {
      wx.makePhoneCall({
        phoneNumber: that.data.supportPhone
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (e) {
    var that = this
    that.setData({
      // swiper_h: app.globalData.swiper_h,
      storeid: app.globalData.storeId,
      // searchbg: app.globalData.searchbg
    })
    if (e.agentId) {
      wx.setStorageSync("agentid", e.agentId);
    }
    if (e.disId) {
      wx.setStorageSync("disid", e.disId);
    }
    var st = 2;
    if (e.st) {
      st = e.st;
    }
    if (e.sl) {
      that.setData({ selList: e.sl });
    }
    that.setData({ st: st });
    wx.setNavigationBarTitle({
      title: wx.getStorageSync('mallName')
    })
    if (e.fromuid) {//通过别人分享的链接打开GetImgsListFour
      console.log("fromuid:" + e.fromuid);
      wx.setStorageSync("fromuid", e.fromuid);

    }
    var getLocationPromisified = util.wxPromisify(that.GetVideoInfo)
    getLocationPromisified({

    }).then(that.ToNavIcon())
      .then(that.GetGoodsList())
      .then(that.newsShow())
      .then(that.getGroupBuyProduct())
      .then(that.getWidgetFloatOne())
      .then(that.getWidgetFloatTwo())
      .then(that.getWidgetFloatThree())
      .then(that.getWidgetFloatFour())
      .catch(function (res) {
        console.error("failed" + res)
      })
  },

  //首页悬浮组件
  getWidgetFloatOne: function () {//左中部
    var that = this;
    wx.request({
      url: app.globalData.host + "/api/Store/GetWidgetList?storeId=" + app.globalData.storeId + "&code=index_pic_area&position=11",
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.Config.length > 0 && res.data.Data.Config[0].CustomerFeatures.length > 0) {
            res.data.Data.Config[0].CustomerFeatures[0].ShowImg = app.globalData.image_logo_banner + res.data.Data.Config[0].CustomerFeatures[0].ShowImg
            that.setData({
              positionBtnO: res.data.Data.Config[0].CustomerFeatures[0]
            })
          }
        }
      },
    })
  },

  getWidgetFloatTwo: function () {//左底部
    var that = this;
    wx.request({
      url: app.globalData.host + "/api/Store/GetWidgetList?storeId=" + app.globalData.storeId + "&code=index_pic_area&position=12",
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.Config.length > 0 && res.data.Data.Config[0].CustomerFeatures.length > 0) {
            res.data.Data.Config[0].CustomerFeatures[0].ShowImg = app.globalData.image_logo_banner + res.data.Data.Config[0].CustomerFeatures[0].ShowImg
            that.setData({
              positionBtnTw: res.data.Data.Config[0].CustomerFeatures[0]
            })
          }
        }
      },
    })
  },
  getWidgetFloatThree: function () {//右中部
    var that = this;
    wx.request({
      url: app.globalData.host + "/api/Store/GetWidgetList?storeId=" + app.globalData.storeId + "&code=index_pic_area&position=13",
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.Config.length > 0 && res.data.Data.Config[0].CustomerFeatures.length > 0) {
            res.data.Data.Config[0].CustomerFeatures[0].ShowImg = app.globalData.image_logo_banner + res.data.Data.Config[0].CustomerFeatures[0].ShowImg
            that.setData({
              positionBtnTh: res.data.Data.Config[0].CustomerFeatures[0]
            })
          }
        }
      },
    })
  },
  getWidgetFloatFour: function () {//右底部
    var that = this;
    wx.request({
      url: app.globalData.host + "/api/Store/GetWidgetList?storeId=" + app.globalData.storeId + "&code=index_pic_area&position=14",
      success: function (res) {
        if (res.data.Code == 0) {
          if (res.data.Data.Config.length > 0 && res.data.Data.Config[0].CustomerFeatures.length > 0) {
            res.data.Data.Config[0].CustomerFeatures[0].ShowImg = app.globalData.image_logo_banner + res.data.Data.Config[0].CustomerFeatures[0].ShowImg
            that.setData({
              positionBtnF: res.data.Data.Config[0].CustomerFeatures[0]
            })
          }
        }
      },
    })
  },

  /**
   * 按钮导航
   */
  ToNavIcon: function () {
    var that = this
    wx.request({
      url: app.globalData.host + '/api/store/GetWidgetList?storeid=' + app.globalData.storeId + '&code=index_nav_icon',
      success: function (res) {
        if (res.data.Code == 0) {
          var newbs = [];
          var rawData = res.data.Data.Config;
          var Widget = res.data.Data.Widget;
          if (Widget.IsActive) {        //是否展示
            if (!Widget.DisplayType) { //分类导航展示方式0-默认，1-横滑
              for (let k = 0; k < rawData.length; k++) {
                rawData[k].ShowImg = app.globalData.image_logo_banner + rawData[k].ShowImg;
              }
              that.setData({
                classifyNav: rawData
              })
            } else {
              for (let h = 0; h < rawData.length; h++) {
                rawData[h].ShowImg = app.globalData.image_logo_banner + rawData[h].ShowImg;
              }
              for (var i = 0, len = rawData.length; i < len; i += 8) {
                newbs.push(rawData.slice(i, i + 8));
              }
              that.setData({
                classify: newbs,
                scrollLeft: 48
              });
            }
          }
        }
      }
    })
  },

  onShow: function () {
    var that = this;
    if (app.globalData.userInfo) {
      console.log("用户信息存在")
      wx.setNavigationBarTitle({
        title: wx.getStorageSync('mallName')
      })
      that.GetSharePagePath()
    } else {
      console.log("用户信息不存在,延时加载")
      setTimeout(function () {
        this.onShow();
      }.bind(that), 1000)
    }
  },
  tapSearch: function (e) {
    wx.navigateTo({
      url: "/pages/classes/index"
    })
  },
  onPullDownRefresh: function () {
    var that = this;
    wx.showToast({
      title: '正在刷新',
      duration: 1500,
      icon: 'loading',
      success: function () {
        that.setData({ CurrentPage: 1 })
        that.GetGoodsList();
      },
      complete: function () {
        wx.stopPullDownRefresh();
      }
    })
  },

  onShareAppMessage: function () { //分享
    return {
      title: wx.getStorageSync('mallName'),
      path: this.data.pathGoods,
      success: function (res) {
        // 转发
        wx.showModal({
          title: '提示',
          content: '转发成功',
          showCancel: false
        })
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  //获取分销商信息
  GetSharePagePath: function () {
    var that = this;
    var disId = wx.getStorageSync('disid')
    var agentId = wx.getStorageSync('agentid')
    if (!disId) {
      disId = 0
    }
    if (!agentId) {
      agentId = 0
    }
    wx.request({
      url: app.globalData.host + '/api/Distributor/GetDistributorAndCreate',
      data: {
        userId: app.globalData.userInfo.Uid,
        storeId: app.globalData.storeId,
        disId: disId,
        agentId: agentId
      },
      success: function (res) {
        if (res.data.Code == 0) {
          var path = '';
          var fromuid = app.globalData.userInfo.Uid;
          if (res.data.Data.IsAgent == 0) {
            path = '/pages/index/index?fromuid=' + fromuid + "&disId=" + res.data.Data.Id + "&agentId=" + res.data.Data.AgentDId
          } else {
            path = '/pages/index/index?fromuid=' + fromuid + "&disId=" + res.data.Data.Id + "&agentId=" + res.data.Data.AgentDId
          }
          that.setData({
            pathGoods: path
          })
        }
      }
    })
  },
  //跳转案例列表
  exampleList: function (e) {
    var newstypeid = e.currentTarget.dataset.newstypeid
    wx.navigateTo({
      url: '/pages/news-list/index?newstypeid=' + newstypeid,
    })
  },
  //跳转文章详情
  toArtcle: function (e) {
    var newsid = e.currentTarget.dataset.newsid
    wx.navigateTo({
      url: '/pages/news-details/index?newsid=' + newsid,
    })
  },
  newsShow: function () {
    var that = this;
    wx.request({
      url: app.globalData.host + '/api/news/StoreNewsTypeList?storeid=' + app.globalData.storeId + '&hasnews=1',
      success: function (res) {
        if (res.data.Code == 0) {
          that.setData({
            newsArray: res.data.Data
          })
        }
      }
    })
  },
})